package com.lzq.badminton.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lzq.badminton.enums.AppHttpCodeEnum;
import com.lzq.badminton.properties.JwtProperties;
import com.lzq.badminton.security.WxAuthenticationToken;
import com.lzq.badminton.service.RoleService;
import com.lzq.badminton.utils.JwtUtil;
import com.lzq.badminton.utils.RedisCache;
import com.lzq.badminton.utils.WebUtils;
import com.lzq.badminton.vo.ResponseResult;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@AllArgsConstructor
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RoleService roleService;
    @Autowired
    private JwtProperties jwtProperties;


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException, ServletException, IOException {
        String token = httpServletRequest.getHeader("access-token");

        if(!StringUtils.hasText(token)){
            //说明该接口不需要登录  直接放行
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        System.out.println(token);
        if (token.length()>30 && !StringUtils.isEmpty(token)) {
            // 从token中获取openId和userId
//            Claims claims =  JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Claims claims = null;
            try {
                claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            } catch (Exception e) {
                e.printStackTrace();
                //token超时  token非法
                //响应告诉前端需要重新登录
                ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_ERROR);
                WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
                return;
            }
            String openId = claims.get("openId").toString();
            Long userId = Long.valueOf(claims.get("userId").toString());
//            String openId = claims.get("openId", String.class);
//            System.out.println(claims.get("userId"));
//            String userIdd =  claims.get("userId", String.class);
//            System.out.println("userIdd:" + userIdd);
//            Long userId =  Long.valueOf(userIdd);



            if (!ObjectUtil.isEmpty(userId) && !ObjectUtil.isEmpty(openId) && SecurityContextHolder.getContext().getAuthentication() == null) {
                log.info("获取" + userId + "的角色");

                //检查redis中的token是否合法
//                String userIdRedis = redisCache.getCacheObject("WxToken:" + token);
//                if(userIdRedis == null){
//                    //登录过期，提示重新登录
//                    ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
//                    WebUtils.renderString(httpServletResponse, JSON.toJSONString(result));
//                    return;
//                }

                List<String> roleKeyList = roleService.selectRoleKeyByUserId(userId, 1);
//                List<SimpleGrantedAuthority> authorityList = roleKeyList
//                        .stream()
//                        .map(roleKey -> new SimpleGrantedAuthority("ROLE_" + roleKey))
//                        .collect(Collectors.toList());

                List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
                for(String roleKey : roleKeyList){
                    SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_" + roleKey);
                    authorityList.add(simpleGrantedAuthority);
                }
                // 将token加入安全上下文
                SecurityContextHolder.getContext().setAuthentication(new WxAuthenticationToken(openId, userId, authorityList));

            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);

    }
}

